package create_container

import (
	link "bridge/link_docker"
	ssh_link "bridge/ssh"
	"context"
	"encoding/json"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/go-connections/nat"
	"github.com/tidwall/gjson"
	"net/http"
)

func Create_container(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	imagename := r.Form["imagename"]
	w.Header().Set("Access-Control-Allow-Origin", "*")
	cli := link.Client()
	resp, err := cli.ContainerCreate(context.Background(), &container.Config{
		Image: imagename[0],
		Tty:   true,
		ExposedPorts: nat.PortSet{
			"22/tcp": {},
		},
	}, &container.HostConfig{
		PortBindings: nat.PortMap{
			"22/tcp": []nat.PortBinding{
				{
					HostIP:   "0.0.0.0",
					HostPort: "0",
				},
			},
		},
	}, nil, nil, "")
	if err != nil {
		panic(err)
	}
	err = cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{})
	if err != nil {
		panic(err)
	}
	containerl, err := cli.ContainerInspect(context.Background(), resp.ID)
	b, err := json.Marshal(containerl)
	fmt.Println(string(b))
	fmt.Fprint(w, string(b))
}

func Create_vnc(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	imagename := r.Form["imagename"]
	w.Header().Set("Access-Control-Allow-Origin", "*")
	cli := link.Client()
	resp, err := cli.ContainerCreate(context.Background(), &container.Config{
		Image: imagename[0],
		Tty:   true,
	}, nil, nil, nil, "")
	if err != nil {
		panic(err)
	}
	err = cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{})
	if err != nil {
		panic(err)
	}
	containerl, err := cli.ContainerInspect(context.Background(), resp.ID)
	b, err := json.Marshal(containerl)
	containerip := gjson.Get(string(b), "NetworkSettings.IPAddress")
	conn, err := ssh_link.PwdConnect("117.50.173.218", "root", "19880228lQy.", 22)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	session, err := conn.NewSession()
	if err != nil {
		panic(err)
	}
	defer session.Close()
	cmd := "docker exec -it cf43855ca0a6 set.sh " + containerip.String()
	fmt.Println(cmd)
	//cmdInfo, err := session.CombinedOutput(cmd)
	//if err != nil {
	//	panic(err)
	//}
	//fmt.Println(string(cmdInfo))
	fmt.Println(string(b))
	fmt.Fprint(w, string(b))

}
